package com.hbnu.gui.constant;

import com.hbnu.gui.util.AlertUtil;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public enum Views {
    LOGIN("登录界面", "/gui/login/fxml/LoginView.fxml", true),
    REGISTER("注册界面", "/gui/register/fxml/RegisterView.fxml", true),
    MAIN("主界面", "/gui/main/fxml/MainView.fxml", true);

    private static final Logger logger = LoggerFactory.getLogger(Views.class);

    private final String desc;          // 界面描述
    private final String fxmlPath;      // FXML文件路径
    private final boolean cacheable;    // 是否允许缓存

    Views(String desc, String fxmlPath, boolean cacheable) {
        this.desc = desc;
        this.fxmlPath = fxmlPath;
        this.cacheable = cacheable;
    }

    public ViewLoadResult load() throws IOException {
        try {
            FXMLLoader loader = new FXMLLoader(Views.class.getResource(fxmlPath));
            Parent root = loader.load();

            return new ViewLoadResult(root, loader.getController());
        } catch (IOException e) {
            logger.error("加载界面[{}]失败：{}", desc, e.getMessage(), e);
            AlertUtil.showAlert(Alert.AlertType.ERROR, "界面加载失败", desc + "加载出错，请检查FXML文件！");
            throw e;    // 抛出异常，让WindowManager处理
        }
    }

    public String getDesc() {
        return desc;
    }

    public String getFxmlPath() {
        return fxmlPath;
    }

    public boolean isCacheable() {
        return cacheable;
    }

    public static class ViewLoadResult {
        private final Parent root;
        private final Object controller;

        public ViewLoadResult(Parent root, Object controller) {
            this.root = root;
            this.controller = controller;
        }

        public Parent getRoot() {
            return root;
        }

        @SuppressWarnings("unchecked")
        public <T> T getController() {
            return (T) controller;
        }
    }
}
